<template>
  <!-- 仓库库龄配置表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800"
    draggable
    @close="closeDialog"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.plantId"
              placeholder="请输入工厂"
              clearable
              @change="changePlant"
              style="width: 230px"
              filterable
            >
              <el-option
                v-for="item in plantList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.plantCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="业务组" prop="workOrganizationId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workOrganizationId"
              placeholder="请输入业务组"
              clearable
              @change="changeWorkOrganization"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="item in workOrganizationList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.workOrganizationName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="配置类型" prop="configType">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.configType"
              placeholder="请选择配置类型"
              clearable
              style="width: 230px"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('ConfigTypeMes')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "ConfigTypeMes",
                formData.configType
              )
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="时间周期(小时)" prop="timePeriod">
            <el-input-number
              v-if="!props.isReadonly"
              v-model="formData.timePeriod"
              :min="1"
              style="width: 100%"
            />
            <span v-else>{{ formData.timePeriod }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
              type="textarea"
            />

            <text v-else>{{ formData.remarks }}</text>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESWAREHOUSEAGECONFIGADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  materialId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请输入工厂", trigger: "change" }],
  timePeriod: [],
  configType: [],
  workOrganizationId: [
    { required: true, message: "请输入业务组", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  warehouseId: "",
  warehouseCode: "",
  warehouseName: "",
  timePeriod: "",
  configType: "",
  workOrganizationId: "",
  workOrganizationCode: "",
  workOrganizationName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        materialId,
        materialCode,
        materialName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        warehouseId,
        warehouseCode,
        warehouseName,
        timePeriod,
        configType,
        workOrganizationId,
        workOrganizationCode,
        workOrganizationName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        materialId,
        materialCode,
        materialName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        warehouseId,
        warehouseCode,
        warehouseName,
        timePeriod,
        configType,
        workOrganizationId,
        workOrganizationCode,
        workOrganizationName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
    formData.configType = String(formData.configType);
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.warehouseId = "";
  formData.warehouseCode = "";
  formData.warehouseName = "";
  formData.timePeriod = "";
  formData.configType = "";
  formData.workOrganizationId = "";
  formData.workOrganizationCode = "";
  formData.workOrganizationName = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);

/** 仓库库龄配置保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/meswarehouseageconfig/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

onMounted(() => {
  getPlantList();
  getWorkOrganizationList();
});
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const changePlant = (id: any) => {
  formData.plantId = id;
  plantList.value.forEach((item: any) => {
    if (item.id === id) {
      formData.plantCode = item.organizationCode;
      formData.plantName = item.organizationName;
    }
  });
};
//业务组列表
const workOrganizationList = ref([]);
const getWorkOrganizationList = async () => {
  const { data } = await request({
    url: "/system/sysbusinessgroup/getlist",
    method: "post",
    data: { enabled: 1, ids: [] },
  });
  workOrganizationList.value = data;
};
const changeWorkOrganization = (id: any) => {
  formData.workOrganizationId = id;
  workOrganizationList.value.forEach((item: any) => {
    if (item.id === id) {
      formData.workOrganizationName = item.name;
    }
  });
};
</script>
